import com.sun.scenario.effect.impl.sw.java.JSWBlend_SRC_INPeer;

import java.util.ArrayList;
import java.util.Arrays;

public class TestHeap {
    public int[] elem;
    public int usedSize;
    public TestHeap() {
        this.elem = new int[10];
    }
    public void initElem(int[] array){
        for (int i = 0; i < array.length;i++ ) {
            elem[i] = array[i];
            usedSize++;
        }
    }
    public void createHead() {
        for (int parent = (usedSize - 1 - 1) / 2;parent >= 0;parent--) {
            siftDown(parent,usedSize);
//            System.out.println();
        }
    }
    public void siftDown(int parent,int usedSize) {
        int child = 2 * parent + 1;
        while(child < usedSize){
            if (child + 1 < usedSize && elem[child] < elem[child+1]) {
                child = child + 1;
            }
            if (elem[parent] < elem[child]) {
                swap(child,parent);
                child = parent * 2 + 1;
            } else {
                break;
            }
        }
    }
    public void swap(int a,int b) {
        int tmp = elem[a];
        elem[a] = elem[b];
        elem[b] = tmp;
    }
    public void push(int val) {
        if (isFull()) {
            elem = Arrays.copyOf(elem,elem.length * 2);
        }
        elem[usedSize] = val;
        siftUp(usedSize);
        usedSize++;
    }
    public boolean isFull() {
        return usedSize == elem.length;
    }
    public void siftUp(int child) {
        int parent = (child -1) / 2;
        while(child > 0) {
            if(elem[child] > elem[parent]) {
                swap(child,parent);
                child = parent;
                parent = (child -1) / 2;
            } else {
                break;
            }
        }
    }
    public int  pop() {
        if (isEmpty()) {
            return -1;
        }
        int oldVal = elem[0];
        swap(0,usedSize - 1);
        return oldVal;
    }
    public boolean isEmpty() {

        return usedSize == 0;
    }
    public void heapSort() {
        int end  = usedSize - 1;
        while(end > 0) {
            swap(0,end);
            siftDown(0,end);
            end--;
        }
    }
}



